package bpm.dao.impl.user;

import java.io.Serializable;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import bpm.dao.user.DepartmentDao;
import bpm.domain.user.Department;

/**
 * 
 * @author <a mailto="hwangsyin@gmail.com">King</a>
 *
 */
@Repository("departmentDao")
public class DepartmentDaoImpl implements DepartmentDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	public void save(Department department) {
		String sql = "insert into bpm_id_dept(id,code,name,rank,create_time,last_update_time,pid) " +
			"values(?,?,?,?,?,?,?)";
		Object[] args = new Object[]{department.getId(), department.getCode(), department.getName(),
			department.getRank(), new Date(department.getCreateTime().getTime()), null, 
			department.getParent() == null ? null : department.getParent().getId()};
		
		this.jdbcTemplate.update(sql, args);
	}

	public Integer nextId() {
		String sql = "select max(id) from bpm_id_dept";
		Integer result = this.jdbcTemplate.queryForInt(sql) + 1;
		return result;
	}

	public Integer maxId() {
		String sql = "select max(id) from bpm_id_dept";
		return this.jdbcTemplate.queryForInt(sql);
	}

	public Department find(Serializable id) {
		StringBuilder sql = new StringBuilder();
		sql.append("select a.id,a.code,a.name,a.rank,a.create_time,a.last_update_time,")
			.append("b.id as p_id,b.code as p_code,b.name as p_name,b.rank as p_rank,b.create_time as p_create_time,b.last_update_time as p_last_update_time ")
			.append("from bpm_id_dept as a left join bpm_id_dept as b on a.pid=b.id ")
			.append("where a.id=?");
		System.out.println(sql);
		
		return (Department)this.jdbcTemplate.queryForObject(sql.toString(), 
			new Object[]{id}, new RowMapper() {
				public Object mapRow(ResultSet rs, int i)throws SQLException {
					Department dept = new Department();
					dept.setId(rs.getInt(1));
					dept.setCode(rs.getString(2));
					dept.setName(rs.getString(3));
					dept.setRank(rs.getInt(4));
					dept.setCreateTime(new Date(rs.getDate(5).getTime()));
					java.sql.Date lastUpdateTime = rs.getDate(6);
					if(lastUpdateTime != null) {
						dept.setLastUpdateTime(new Date(lastUpdateTime.getTime()));
					}
					
					Integer pid = rs.getInt(7);
					if(pid != null && pid != 0) {
						dept.setParent(new Department(pid));
						dept.getParent().setCode(rs.getString(8));
						dept.getParent().setName(rs.getString(9));
						dept.getParent().setRank(rs.getInt(10));
						dept.getParent().setCreateTime(new Date(rs.getDate(11).getTime()));
						
						java.sql.Date lastUpdateTime2 = rs.getDate(12);
						if(lastUpdateTime2 != null) {
							dept.getParent().setLastUpdateTime(new Date(lastUpdateTime2.getTime()));
						}
					}
					return dept;
				}
			
		});
	}
}
